//
//  ByUIAppIndexNewVC.m
//  chequanbao_ios
//
//  Created by mc on 2017/10/24.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIAppIndexNewVC.h"
// service
#import "ByCoreToolLocation.h"              // 定义服务

// vc
#import "ByUIIndexLocationVC.h"             // 定位
#import "ByUIMineWelfareVC.h"               // 我的福利
#import "ByUIShopsDetailVC.h"
#import "ByUIShopsIndexVC.h"                // 商家列表
// view
#import "ByViewDetailHeaderCarousel.h"      // 轮播视图
#import "ByViewRedPicket.h"                 // 红包
#import "ByViewLocation.h"                  // 导航
#import "ByHomeAdvertView.h"                // 公司热点
#import "ByViewIndexSearch.h"               // 搜索

// api
#import "ByApiAppIndex.h"
#import "ByNetConfigApi.h"
// cell
#import "ByCellIndexFuction.h"

// model
#import "ByModelIndexCarousel.h"
@interface ByUIAppIndexNewVC ()<UITableViewDelegate,UITableViewDataSource,ByCoreLoactionDelegate,UISearchBarDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView                        *locationView;    // 定位
@property (nonatomic, strong) ByViewDetailHeaderCarousel    *carousel_top;    // 轮播

@property (nonatomic, strong) ByViewRedPicket               *rpView;          // 红包
@property (nonatomic, strong) ByViewLocation                *dhView;          // 导航
@property (nonatomic, strong) ByHomeAdvertView              *hotView;         // 公司热点

@property (nonatomic, strong) NSArray                       *hotsArray;       // 热点
@end

@implementation ByUIAppIndexNewVC
{
    NSString *_city;            // 定位城市或者选择城市
    
    // 请求轮播
    BOOL _didLoadCarsouel;
    int _loadCount;
    
    // 请求公司热点
    BOOL _didLoadHots;
    int _loadHotCount;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title = @"首页";
    // 创建搜索框
    [self createNaviItems];
    
    // 展示红包
    [self needShowRedPacket];
    
    [self addBYItemviews:@[@"定位"] mode:ByNavigationItemModeText position:ByNavigationItemPositionModeLeft];
    [self addBYItemviews:@[@"Index_daohang"] mode:ByNavigationItemModeImage position:ByNavigationItemPositionModeRight];
    [self createCityLocationView];
    [self createCarousel_top];
    [self initTable];
    // 定位
    [self location];
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];
    // 还没请求到轮播
    if (!_didLoadCarsouel) {
        _loadCount = 0;
        [self getCarousel];
    }
    
    if (!_didLoadHots) {
        _didLoadHots = 0;
        [self getHots];
    }
}

- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    self.carousel_top.top = self.view.safeAreaInsets.top;
    self.tableView.top = self.carousel_top.bottom;
    self.tableView.height = self.view.height - self.view.safeAreaInsets.bottom - 49 - self.view.safeAreaInsets.top - self.carousel_top.height;
}

- (void)rightItemsAction:(NSInteger)rightIndex{
    [self.dhView show];
}

#pragma mark - 懒加载
- (ByViewRedPicket *)rpView {
    
    if (!_rpView) {
        _rpView = [[ByViewRedPicket alloc] init];
        __weak typeof(self) wself = self;
        _rpView.rpTapBlock = ^ {
            
            [wself by_normalPush:[ByUIMineWelfareVC new] hasNavi:YES];
        };
    }
    return _rpView;
}

- (ByViewLocation *)dhView{
    if (!_dhView) {
        _dhView = [[ByViewLocation alloc] init];
        __weak typeof(self) wkself = self;
        _dhView.clickBlock = ^(NSInteger index) {
            if (index == 0) {
                [wkself baiduMap];
            }else{
                [wkself gaodeMap];
            }
        };
        
    }
    return _dhView;
}

- (NSArray *)hotsArray{
    if (!_hotsArray) {
        _hotsArray = [NSArray array];
    }
    return _hotsArray;
}

- (ByHomeAdvertView *)hotView{
    if (!_hotView) {
        _hotView = [[ByHomeAdvertView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80) timerDuration:5];
    }
    return _hotView;
}

#pragma mark - 导航
// 百度地图
- (void)baiduMap{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]])// -- 使用 canOpenURL 判断需要在info.plist 的 LSApplicationQueriesSchemes 添加
    {
        //        double latitude =self.coordinate.latitude;
        //        double longitude =self.coordinate.longitude;
        NSString *urlString = @"baidumap://map";
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *mapUrl = [NSURL URLWithString:urlString];
        [[UIApplication sharedApplication] openURL:mapUrl];
        
        
        
    }else{
        
        [[[UIAlertView alloc]initWithTitle:@"没有安装百度地图" message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil, nil] show];
    }
}

// 高德地图
- (void)gaodeMap{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]){
        NSString *urlString = @"iosamap://path";
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *mapUrl = [NSURL URLWithString:urlString];
        [[UIApplication sharedApplication] openURL:mapUrl];
        
    }else{
        
        [[[UIAlertView alloc]initWithTitle:@"没有安装高德地图" message:@"" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
    }
}

#pragma mark - 定位
- (void)location {
    
    [ByCoreToolAlert showLoadind:@"正在定位..."];
    ByCoreToolLocation *locationManager = [ByCoreToolLocation shareInstance];
    locationManager.delegate = self;
    [locationManager configLocationService];
    [locationManager startUpdateLoaction];
}
- (void)locationDidComplete:(NSDictionary *)placeInfoDic {
    
    [ByCoreToolAlert hideHud];
    
    // 更新当前显示的城市
    _city = placeInfoDic[@"city"];
    [self updateLocation];
    
    // 设置定位城市
    BY_APPDELEGATE.locationCity = _city;
    BY_APPDELEGATE.locationDic = placeInfoDic;
    
}
- (void)locationDidFail:(NSError *)error {
    [ByCoreToolAlert showOnlyText:@"定位失败"];
}
- (void)updateLocation {
    
    UILabel *cityLabel = [self.locationView viewWithTag:2];
    cityLabel.text = _city;
}

#pragma mark - 网络请求
// 请求热点
- (void)getHots{
    _didLoadHots = YES;
    [ByNetConfigApi requestRemoteGlobalConfigSuccess:^(ByNetBaseResult *result) {
        NSLog(@"%@",result.data);
        if ([result.data[@"SCROLL_TEXT"] isKindOfClass:[NSArray class]]) {
            self.hotsArray = [result.data[@"SCROLL_TEXT"] copy];
            [self.tableView reloadData];
        }
        _didLoadHots = YES;
        
    } failure:^(ByNetBaseResult *result) {
//        [ByCoreToolAlert showOnlyText:result.msg];
        _didLoadHots = NO;
        [self performSelector:@selector(timerHotAction) withObject:nil afterDelay:5];

    }];
}

- (void)timerHotAction{
    if (_loadHotCount >= 3) {
        NSLog(@"超过3次了，不请求了");
        [self.tableView reloadData];
        return;
    } else {
        NSLog(@"定时器，请求");
        _loadHotCount ++;
        [self getHots];
    }
    
}

// 轮播
- (void)getCarousel {
    
    ByNetParamsModel *params = [ByNetParamsModel new];
    params.position = @"6079";
    
    [ByApiAppIndex getIndexCarousel:params success:^(ByNetBaseResult *result) {
        
//        NSArray<ByModelIndexCarousel *> *carousels = result.data;
//        NSMutableArray *imageUrlStrs = [NSMutableArray new];
//        [carousels enumerateObjectsUsingBlock:^(ByModelIndexCarousel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            [imageUrlStrs addObject:BOYE_PICTURE_VIEW_URL(obj.img)];
//        }];
        
//        self.carousel_top.imageURLStringDatas = imageUrlStrs.copy;
        self.carousel_top.imageURLStringDatas = [result.data copy];
        __weak typeof(self) weakSelf = self;
        self.carousel_top.itemDidTap = ^(NSInteger index) {
            ByModelIndexCarousel *model = weakSelf.carousel_top.imageURLStringDatas[index];
            NSLog(@"%@",model.storeid);
            if (![model.storeid isEqualToString:@"-1"] && ![model.storeid isEqualToString:@"0"] && model.storeid.length != 0) {
                ByUIShopsDetailVC *vc = [[ByUIShopsDetailVC alloc] init];
                vc.type = model.storeid;
                [weakSelf by_normalPush:vc hasNavi:YES];
            }
        };
        _didLoadCarsouel = YES;
    } failure:^(ByNetBaseResult *result) {
        self.carousel_top.imageURLStringDatas = @[@"default"];
        [ByCoreToolAlert showFailureWithText:@"轮播图获取失败"];
        _didLoadCarsouel = NO;
        [self performSelector:@selector(timerActions) withObject:nil afterDelay:5];
    }];
}
- (void)timerActions {
    if (_loadCount >= 3) {
        NSLog(@"超过3次了，不请求了");
        return;
    } else {
        NSLog(@"定时器，请求");
        _loadCount ++;
        [self getCarousel];
    }
}
#pragma mark - create views
- (void)createNaviItems {
    ByViewIndexSearch *searchView = [[ByViewIndexSearch alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 0.7 - 40, 30)];
    searchView.searchBlock = ^(NSString *searchText) {
        ByUIShopsIndexVC *vc = [[ByUIShopsIndexVC alloc] init];
        vc.searchName = searchText;
        [self by_normalPush:vc hasNavi:YES];
    };
    self.navigationItem.titleView = searchView;
}
// 创建导航栏视图
- (void)createCityLocationView {
    
    self.locationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH * 0.2, 30)];
    self.locationView.backgroundColor = [UIColor clearColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(locationTap:)];
    [self.locationView addGestureRecognizer:tap];
    
    UIImageView *downIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    downIcon.image = [UIImage imageNamed:@"Index_jiantou_down"];
    [self.locationView addSubview:downIcon];
    downIcon.right = self.locationView.width - 10;
    downIcon.y = self.locationView.height / 2;
    downIcon.tag = 1;
    
    UILabel *cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, downIcon.left, self.locationView.height)];
    cityLabel.font = FONT(14);
    cityLabel.text = @"选择";
    cityLabel.textColor = [UIColor whiteColor];
    cityLabel.textAlignment = NSTextAlignmentCenter;
    [self.locationView addSubview:cityLabel];
    cityLabel.tag = 2;
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:self.locationView];
    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)createCarousel_top {
    self.carousel_top = [[ByViewDetailHeaderCarousel alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_WIDTH * 8 / 15) timerDuration:3];
    [self.view addSubview:self.carousel_top];
}

- (void)initTable{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.carousel_top.bottom, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - self.carousel_top.height - 49)];
    [self.view addSubview:_tableView];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;

}


#pragma mark - UITableViewDelegate,UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 公司热点
    if (indexPath.row == 0) {
        static NSString *indentier = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentier];
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell addSubview:self.hotView];
        }
        if (self.hotsArray.count != 0) {
            self.hotView.advertAry = self.hotsArray;
        }
        if (!_didLoadHots) {
            cell.hidden = YES;
        }else{
            cell.hidden = NO;
        }

        return cell;

    }
    // 功能模块
    else{
        ByCellIndexFuction *cell = [ByCellIndexFuction cellWithTableView:tableView];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        if (!_didLoadHots) {
            return 0;
        }
        return 80;
    }
    else{
        CGFloat m_h, m_v,width,height;
        m_h = 10;
        m_v = 10;
        width = (SCREEN_WIDTH - 3 * m_h) / 2;
        height = (width / 335 * 160) * 2;
        width = SCREEN_WIDTH - 10 * 2;
        return height + 10 + width / 690 * 160 + 20;
    }
}



#pragma mark - 逻辑
// 是否需要展示红包
#define KIsFirstUse @"isFirstUse"
- (BOOL)needShowRedPacket {
    
    NSNumber *isFirstUse = [ByCoreCacheSqlite3 getValueWithKey:KIsFirstUse];
    // 没有设置过值，就说明是第一次
    if ( isFirstUse == nil) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_after(dispatch_time(0, NSEC_PER_SEC * 0.5), dispatch_get_main_queue(), ^{
                [self.rpView show];
            });
        });
        [ByCoreCacheSqlite3 setObjectWithKey:KIsFirstUse value:@YES];
        return YES;
    } else {
        return NO;
    }
    
}
- (void)locationTap:(UITapGestureRecognizer *)tap {
    
    ByUIIndexLocationVC *vc = [[ByUIIndexLocationVC alloc] init];
    [self by_normalPush:vc hasNavi:YES];
    vc.locationDidSelected = ^(ByModelLocationCity *cityModel) {
        
        BY_APPDELEGATE.selectedCityModel = cityModel;
        _city = cityModel.city;
        [self updateLocation];
    };
    
}
@end
